;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.PlanDealer", [])
        .controller("PlanDealerCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "ybConfig", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", "$stateParams", function ($scope, $state, ybWidget, ybHttp, ybConfig, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter, $stateParams) {
            $scope.activeFlag = [true, false, false];
            $scope.showDatepickerBegin = false;
            $scope.showDatepickerEnd = false;
            $scope.showDatedeliveryReceiptStart = false;
            $scope.showDatedeliveryReceiptEnd = false;
            $scope.submitted = false;
            $scope.viewModel = null
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
            };
            $scope.tabFlag = {};
            $scope.orderObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.dataList = [];
            $scope.deliveryWayList = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑"
            };

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/buyPlanDealer/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/buyPlanDealer/exportAll")
            };
            // 切换时间选择器
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };
            $scope.sendMethodList = [];
            $scope.billStateList = [];
            $scope.tableConfig = {
                fixedWidth: 270,
                scrollWidth: 1400,
                tableCol: [
                    {
                        type: "",
                        name: "计划单号",
                        dataField: "buyPlanNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "经销商名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "提报日期",
                        dataField: "presentDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 150,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                fixedWidth: 340,
                scrollWidth: 870,
                tableCol: [
                    {
                        name: "序号",
                        width: 60,
                        dataField: "rowNo",
                        isShow: false,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialsNo",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 180,
                        dataField: "materialsDesc",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        isShow: true,
                        needInput: false
                    },

                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "planNum",
                        isShow: true,
                        needInput: true
                    },
                ]
            };

            var btnPermissionCode = {
                planDealerAdd: window.ActionCode.planDealerAdd,
                planDealerEdit: window.ActionCode.planDealerEdit,
                planDealerRevert: window.ActionCode.planDealerRevert,
                planDealerDel: window.ActionCode.planDealerDel,
            };

            $scope.btnPermission = {
                planDealerAdd: true,
                planDealerEdit: true,
                planDealerRevert:true,
                planDealerDel: true,

            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };



            function handleSpecialTabCol(showFlag, purchaseInputFlag, transferInputFlag) {
                if (!$scope.isJCH) return;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'purchaseQty').needInput = purchaseInputFlag;
                 // 农机定制
                $scope.isNJ && (ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'price').needInput = purchaseInputFlag)
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferAmount').needInput = transferInputFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferBillNo').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferStatusName').isShow = showFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'fwAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'fwFtmAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'bjAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'dcAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'warehouseCode').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'areaCode').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferAmount').isShow = showFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'supplierName').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'batchNo').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'reservedOrder').isShow = showFlag;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/buyPlanDealer/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                for (var key in $scope.condition) {
                    if ($scope.condition[key] == "") {
                        $scope.condition[key] = undefined;
                    }
                }
                param.filters = $scope.condition;
                param.dateStart = param.dateStart ?   $filter("YbDate")(param.dateStart, 'yyyy-MM-dd') : ''
                param.dateEnd = param.dateEnd ?   $filter("YbDate")(param.dateEnd, 'yyyy-MM-dd') : ''
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    let status = {
                        0:"已保存",
                        1:"已提交",
                        2:"已确认"
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.presentDateShow = $filter("YbDate")(item.presentDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = status[item.status]
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType, fieldName) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'amount').isShow = false;
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "selectWarehouse":
                        selectWarehouse(item, fieldName);
                    default:
                        break;
                }
            };

            $scope.selectDealer = function () {
                const options = {
                    title: '经销商',
                    service: 'device',
                    url: '/companyDealer/list',
                    // otherParams: { isPlatCompany: true },
                    keyWords: [{label: '客户编号', field: 'dealerCode'}, {label: '客户名称', field: 'companyName'}],
                    fields: [
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        },
                        {
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                    ]
                }
                ybWidget.DataSelector(options).then(function (data) {
                    console.log(data)
                    $scope.orderObj.headerInfo.dealerOrgName = data.companyName
                    $scope.orderObj.headerInfo.dealerOrgId = data.dealerOrgId
                })
            };

            $scope.clearDealer = function() {
                $scope.orderObj.headerInfo.dealerOrgName = ''
                $scope.orderObj.headerInfo.dealerOrgId = ''
            };
            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            function selectWarehouse(item, fieldName) {
                if (!item[fieldName]) return;

                let wType = ''
                switch(fieldName) {
                    case "fwAmount":
                        wType = 'fwInfo'
                        break;
                    case "fwFtmAmount":
                        wType = 'fwFtmInfo'
                        break;
                    case "bjAmount":
                        wType = 'bjInfo'
                        break;
                    case "dcAmount":
                        wType = 'dcInfo'
                        break;
                }
                const stockType = item.stockInfo[wType].stockType
                ybWidget.DataSelector({
                    title: '库存',
                    url: '/warehouseInventory/listWarehouseInfoByMaterials',
                    otherParams: { materialsNo: item.materialsNo, stockType },
                    isNotFilterParam: true,
                    fields: [
                        {
                            name: '仓库',
                            dataField: 'warehouseCode',
                            width: "40%"
                        },
                        {
                            name: '库区',
                            dataField: 'areaCode',
                            width: "40%"
                        },
                        {
                            name: '数量',
                            dataField: 'qty',
                            width: "20%"
                        },
                    ]
                }).then(function (data) {
                    item.stockType = stockType
                    item.warehouseCode = data.warehouseCode
                    item.areaCode = data.areaCode
                    item.transferAmount = data.qty == 0 ? item.purchaseQty : Math.min(item.purchaseQty, data.qty);
                    $scope.checkTransferAmount(item, 'transferAmount');
                })
            }

            $scope.clearWarehouseAndArea = function(item) {
                item.warehouseCode = '';
                item.areaCode = '';
                item.transferAmount = null;
                item.transferAmountErr = false;
                item.transferAmountExceedErr = false;
                item.transferAmountShowErr = false;
            }

            $scope.searchAddress = function (receiverName, purchaseOrgId) {
                if (!purchaseOrgId) {
                    ybWidget.ShowToaster('warning', '请先选择客户');
                    return;
                }
                ybWidget.SelectDeliveryAddress({
                    deliveryName: receiverName,
                    clientReceiveInfo: $scope.sapNum,
                    clientOrgId: purchaseOrgId,
                    supplierOrgId: $scope.orderObj.headerInfo.orgId
                }).then(function (data) {
                    $scope.orderObj.headerInfo.receiverName = data.receiverName;
                    $scope.orderObj.headerInfo.receiverPhone = data.receiverTel;
                    $scope.orderObj.headerInfo.receiverAddress = data.receiverAddress;
                });
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                };
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };


            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailList[i].isChecked) {
                            $scope.orderObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除的三包申请', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/threeGuaranteesPur/delete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/buyPlanDealer/remove?id=" + id;
                    ybHttp.Post(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.orderObj = {
                    headerInfo:{
                        years: new Date(),
                        months: new Date().getMonth() + 1,
                    },
                    detailList: []
                }

                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                //  工厂端赋值
                if ($scope.curOrg.companyType == 1) {
                    $scope.orderObj.headerInfo.supplierOrgId = $scope.curOrg.orgId
                    $scope.orderObj.headerInfo.supplierOrgName = $scope.curOrg.companyName
                }
                // 经销商赋值
                if ($scope.curOrg.companyType == 2) {
                    $scope.orderObj.headerInfo.dealerOrgId = $scope.curOrg.orgId
                    $scope.orderObj.headerInfo.dealerOrgName = $scope.curOrg.companyName
                }
                $scope.changeTab(2);
                $scope.fileList = [];
            };


            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/buyPlanDealer/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };

            function handleMaterialDetailsWhenSourceType1(tInputFlag) {
                handleSpecialTabCol(true, false, tInputFlag);
                angular.forEach($scope.orderObj.detailList, r => {
                    const si = r.stockInfo;
                    if (si) {
                        r.fwAmount = si.fwInfo && si.fwInfo.amount;
                        r.fwFtmAmount = si.fwFtmInfo && si.fwFtmInfo.amount;
                        r.bjAmount = si.bjInfo && si.bjInfo.amount;
                        r.dcAmount = si.dcInfo && si.dcInfo.amount;
                    }
                })
            }

            $scope.editApply = function (item) {
                $scope.fileList = [];
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.years = new Date($scope.orderObj.headerInfo.years)
                    $scope.orderObj.detailList = data.materialList
                    $scope.changeTab(2);
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    };
                    $scope.orderObj = data;
                    $scope.orderObj.detailList = data.materialList
                    $scope.changeTab(3);
                });
            }



            // 文件上传和查看
            $scope.openFileUploader = function () {
                ybWidget.FileUploader({fileList: $scope.fileList}).then(res => {
                  $scope.fileList = res.fileList;
                })
            };

            // 文件查看
            $scope.openFileViewer = function () {
                ybWidget.FileUploader({fileList: $scope.orderObj.headerInfo.attachFileList, Type: 'view'})
            }

            $scope.viewImage = function (item) {
                ybWidget.ViewImage({
                    FileUrl: item
                })
            };

            $scope.revertApply = function (item) {
                ybWidget.ShowMessage("是否要确认？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/buyPlanDealer/verify";
                    ybHttp.Post(service, reqUrl, [item.id]).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "采购计划",
                    templateReqService: "device",
                    templateReqUrl: "/buyPlanDealer/download",
                    importReqService: "device",
                    importReqUrl: "/buyPlanDealer/importBuyPlanDealer",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.detailList = [];
                    $scope.orderObj.detailList = angular.copy(data);
                });
            };


            // 上传图片
            $scope.fileList = [];
            // 组装图片和文件数据
            function getAttachFileList() {
              let attachFileList = $scope.fileList.filter(item => !!item.fileUrl).map(item =>({
                originFileName: item.filename == item.name ? item.filename : item.name,
                fileUrl: item.fileUrl,
              }))
              return attachFileList;
            }

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.orderObj.headerInfo.attachFileList = getAttachFileList();
                var service = "device";
                var reqUrl = "/buyPlanDealer/save";
                if (!!$scope.orderObj.headerInfo.id) {
                    reqUrl = "/buyPlanDealer/submit";
                }
                if (type === 'submit') {
                    reqUrl = "/buyPlanDealer/submit";
                }
                if (!$scope.orderObj.detailList || $scope.orderObj.detailList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var listValid = true;
                for (var item of $scope.orderObj.detailList) {

                    if ($scope.checkRequired(item, 'planNum')) {
                        listValid = false;
                        break;
                    }

                }
                if (!listValid) {
                    return;
                }

                var param = angular.copy($scope.orderObj);
                param.materialList = param.detailList
                delete param.detailList
                console.log(param)
                console.log(typeof(param.headerInfo.years))
                if (typeof(param.headerInfo.years) != String) {
                    param.headerInfo.years = param.headerInfo.years.getFullYear()
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };




            $scope.auditPurchase = function (type, id, message) {
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/auditPass";
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    reqUrl = "/threeGuaranteesPur/auditRefused";
                }
                var param = {
                    id: id,
                    auditNote: message
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (type === "pass") {
                        ybWidget.ShowMessage("审核成功，是否立即创建三包出库单？", MESG_TYPE.Ask).then(function () {
                            EventBus.Publish('go2otherMenuPage', {
                                name: "app.stock.guaranteesOut",
                                params: {
                                    id: resp.value
                                }
                            });
                        }, function () {

                        })
                    }

                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.orderObj.headerInfo.auditNote = "";
                });
            };




            // 选择运输方式
            $scope.sendMethodChange = function (item) {
                if (item) {
                    $scope.autoAddObj.shippingMethodId = item.code;
                } else {
                    $scope.autoAddObj.shippingMethodId = undefined;

                }
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };


            $scope.selectSapName = function () {
                var param = {
                    name: "内部订单号",
                    type: "sapSel"
                };
                ybWidget.SingleSelector(param).then(function (data) {

                    $scope.orderObj.headerInfo.sapName = data.name;
                    $scope.orderObj.headerInfo.sapId = data.code;
                    var service = "device";
                    var reqUrl = "/innerOrder/getInnerOrderByNo";
                    var param = {orderNo: $scope.orderObj.headerInfo.sapId};

                    ybHttp.Get(service, reqUrl, param).then(function (resp) {

                        if (resp.code == 0) {
                            $scope.orderObj.headerInfo.sapTypeName = resp.value.sapTypeName;
                            $scope.orderObj.headerInfo.guaranteesTypeName = resp.value.guaranteesTypeName;
                            // if(  $scope.orderObj.headerInfo.sapTypeName === null || $scope.orderObj.headerInfo.sapTypeName  === undefined )
                            // {
                            //     $scope.orderObj.headerInfo.sapTypeName = resp.value.sapTypeName;
                            // }
                            // if(  $scope.orderObj.headerInfo.guaranteesTypeName === null || $scope.orderObj.headerInfo.guaranteesTypeName  === undefined )
                            // {
                            //     $scope.orderObj.headerInfo.guaranteesTypeName = resp.value.guaranteesTypeName;
                            // }



                        }

                    });
                })
            };

            $scope.selectDispatch = function () {
                var param = {
                    name: "三包申请调度员",
                    defaultRoleName: '',
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.countTotal = function (item, type) {
                $scope.checkRequired(item, type);

                item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.purchaseQty, item.price), 2);
            };

            $scope.checkTransferAmount = function(item, type) {
                if (!$scope.isJCH || $scope.orderObj.headerInfo.sourceType != 1) return false;

                if (!item.warehouseCode) {
                    // 没有选择（备件库存或大厂库存时，调拨数量字段不作校验）
                    return false;
                }

                if ($scope.checkRequired(item, type)) {
                    item[type+"ExceedErr"] = false;
                    return true;
                }
                return $scope.checkExceedPurchaseQty(item, type);
            };

            $scope.checkExceedPurchaseQty = function (item, type) {
                if (item[type] > item.purchaseQty) {
                    item[type+"ExceedErr"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"ExceedErr"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"ExceedErr"]
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"Err"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"Err"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"Err"]
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]||!!item[type+"ExceedErr"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            (function () {
                getDataList();
                setBtnPermission();
                $scope.setFixedWidth();


            })();
        }]);
})(window, window.angular);
